﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SN.Data;
using Agro.Models;
using System.Web.Security;
using System.Web;
using System.Web.Script.Serialization;

namespace Agro.Services {
    public class LogonService : BaseService, ILogonService {

        public bool UserLogon(string userName, string password,string type,out string msg) {
            msg = string.Empty;
            string encryptPassword;
            //encryptPassword = SN.Core.Helper.Cryptography.MD5Encrypt(password);//密码通过md5加密，暂不用
            encryptPassword = password;
            try
            {
                T_User user = DB.Single<T_User>(T_User._.User_Code == userName && T_User._.User_Password == encryptPassword);
                if(user==null)
                {
                    msg = "用户名或密码不正确";
                    return false;
                }
                T_Organization organization = GetEntity<T_Organization>(T_Organization._.Organization_ID == user.User_OrganizationID);
                if (organization.Organization_Type != type)
                {
                    msg = "用户所选择的入口不正确，如果是管理用户，请选择【管理部门登录】入口，如果是龙头企业监测用户，请选择【龙头企业监测】入口！";
                    return false;
                }
                else
                {
                    user.UserType = int.Parse(organization.Organization_Type);
                    JavaScriptSerializer jss = new JavaScriptSerializer();
                    FormsAuthenticationTicket authTicket = new
                           FormsAuthenticationTicket(1,
                           userName,
                           DateTime.Now,
                           DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes)
                           , false, jss.Serialize(user));
                    string encTicket = FormsAuthentication.Encrypt(authTicket);
                    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
                    System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
                    System.Web.HttpContext.Current.Session["CurrUserInfo"] = user;

                    return true;
                }
               
            }
            catch (Exception ex)
            {
                msg = "连接数据库失败!";
            }
            return false;
        }

        public void Logout() {
            FormsAuthentication.SignOut();
        }
    }
}
